// 保存当前舵机角度
let currentPanAngle = 135;
let currentTiltAngle = 135;
let isDragging = false;
let lastMouseX = 0;
let lastMouseY = 0;
let servoUpdateTimeout = null;

// 初始化页面时更新滑块和虚拟舵机
window.onload = function() {
    document.getElementById('pan-slider').value = currentPanAngle;
    document.getElementById('tilt-slider').value = currentTiltAngle;
    document.getElementById('pan-value').textContent = currentPanAngle;
    document.getElementById('tilt-value').textContent = currentTiltAngle;
    
    // 更新角度信息显示
    // let angleInfoElem = document.querySelector('.angle-info');
    // if (angleInfoElem) angleInfoElem.textContent = `水平: ${currentPanAngle}° | 垂直: ${currentTiltAngle}°`;
    
    // 添加键盘控制
    setupKeyboardControl();
    
    // 延时更新状态信息（等待初始化完成）
    setTimeout(function() {
        document.getElementById('status').innerText = '系统就绪，使用滑块控制云台位置';

        // 添加成功反馈动画
        const statusElement = document.getElementById('status');
        statusElement.classList.add('success-animation');
        setTimeout(() => {
            statusElement.classList.remove('success-animation');
        }, 1000);
    }, 2000); // 等待2秒（系统初始化时间）
};

// 更新滑块值显示和虚拟舵机
function updateSliderValue(sliderId, valueId) {
    const sliderValue = document.getElementById(sliderId).value;
    document.getElementById(valueId).textContent = sliderValue;
    
    if (sliderId === 'pan-slider') {
        currentPanAngle = parseInt(sliderValue);
    } else if (sliderId === 'tilt-slider') {
        currentTiltAngle = parseInt(sliderValue);
    }
    
    // 更新角度信息显示
    // let angleInfoElem = document.querySelector('.angle-info');
    // if (angleInfoElem) angleInfoElem.textContent = `水平: ${currentPanAngle}° | 垂直: ${currentTiltAngle}°`;
    
    // 更新3D舵机模型
    // if (typeof updateServo3D === 'function') {
    //     updateServo3D(currentPanAngle, currentTiltAngle);
    // }
}

// 设置键盘控制
function setupKeyboardControl() {
    document.addEventListener('keydown', function(e) {
        let panChange = 0;
        let tiltChange = 0;
        
        // 方向键控制
        switch(e.key) {
            case 'ArrowLeft':
                panChange = -5;
                break;
            case 'ArrowRight':
                panChange = 5;
                break;
            case 'ArrowUp':
                tiltChange = -5;
                break;
            case 'ArrowDown':
                tiltChange = 5;
                break;
        }
        
        if (panChange !== 0 || tiltChange !== 0) {
            // 更新角度
            currentPanAngle = Math.max(0, Math.min(270, currentPanAngle + panChange));
            currentTiltAngle = Math.max(0, Math.min(270, currentTiltAngle + tiltChange));
            
            // 更新滑块和显示
            document.getElementById('pan-slider').value = currentPanAngle;
            document.getElementById('tilt-slider').value = currentTiltAngle;
            document.getElementById('pan-value').textContent = currentPanAngle;
            document.getElementById('tilt-value').textContent = currentTiltAngle;
            
            // 更新角度信息显示
            // let angleInfoElem = document.querySelector('.angle-info');
            // if (angleInfoElem) angleInfoElem.textContent = `水平: ${currentPanAngle}° | 垂直: ${currentTiltAngle}°`;
            
            // 发送命令
            clearTimeout(servoUpdateTimeout);
            servoUpdateTimeout = setTimeout(function() {
                if (panChange !== 0) moveServo(window.PAN_PIN, currentPanAngle);
                if (tiltChange !== 0) moveServo(window.TILT_PIN, currentTiltAngle);
            }, 100);
            
            // 防止页面滚动
            e.preventDefault();
        }
    });
}

// 控制舵机
function moveServo(pin, angle) {
    document.getElementById('status').innerText = '正在发送命令...';
    
    fetch('/move_servo', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            pin: pin,
            angle: angle
        }),
    })
    .then(response => response.json())
    .then(data => {
        document.getElementById('status').innerText = data.message;
        
        // 添加成功反馈动画
        const statusElement = document.getElementById('status');
        statusElement.classList.add('success-animation');
        setTimeout(() => {
            statusElement.classList.remove('success-animation');
        }, 1000);
    })
    .catch((error) => {
        console.error('Error:', error);
        document.getElementById('status').innerText = '操作失败: ' + error;
        
        // 添加失败反馈动画
        const statusElement = document.getElementById('status');
        statusElement.classList.add('error-animation');
        setTimeout(() => {
            statusElement.classList.remove('error-animation');
        }, 1000);
    });
}

// 发送滑块值
function sendSliderValue(pin, sliderId) {
    const angle = document.getElementById(sliderId).value;
    moveServo(pin, angle);
}

// 重置舵机位置
function resetPosition() {
    document.getElementById('status').innerText = '正在重置位置...';
    
    fetch('/reset_position', {
        method: 'POST',
    })
    .then(response => response.json())
    .then(data => {
        document.getElementById('status').innerText = data.message;
        
        // 更新滑块和虚拟舵机显示
        let panSlider = document.getElementById('pan-slider');
        if (panSlider) panSlider.value = 135;
        let tiltSlider = document.getElementById('tilt-slider');
        if (tiltSlider) tiltSlider.value = 135;
        let panValueElem = document.getElementById('pan-value');
        if (panValueElem) panValueElem.textContent = 135;
        let tiltValueElem = document.getElementById('tilt-value');
        if (tiltValueElem) tiltValueElem.textContent = 135;
        
        // 更新当前角度值
        currentPanAngle = 135;
        currentTiltAngle = 135;
        
        // 更新角度信息显示
        // let angleInfoElem = document.querySelector('.angle-info');
        // if (angleInfoElem) angleInfoElem.textContent = `水平: ${currentPanAngle}° | 垂直: ${currentTiltAngle}°`;
        
        // // 发送命令到舵机 - 注释掉，因为后端已经处理了重置
        // moveServo(window.PAN_PIN, currentPanAngle);  // 水平舵机
        // setTimeout(() => {
        //     moveServo(window.TILT_PIN, currentTiltAngle);  // 垂直舵机
        // }, 100);
    })
    .catch((error) => {
        console.error('Error:', error);
        document.getElementById('status').innerText = '操作失败: ' + error;
    });
}



// 统一更新滑块UI的函数
function updateSliderUI(panAngle, tiltAngle) {
    const panSlider = document.getElementById('pan-slider');
    const tiltSlider = document.getElementById('tilt-slider');
    const panValueElem = document.getElementById('pan-value');
    const tiltValueElem = document.getElementById('tilt-value');
    // const angleInfoElem = document.querySelector('.angle-info'); // 如果存在

    if (panSlider) panSlider.value = panAngle;
    if (tiltSlider) tiltSlider.value = tiltAngle;
    if (panValueElem) panValueElem.textContent = Math.round(panAngle);
    if (tiltValueElem) tiltValueElem.textContent = Math.round(tiltAngle);
    // if (angleInfoElem) angleInfoElem.textContent = `水平: ${Math.round(panAngle)}° | 垂直: ${Math.round(tiltAngle)}°`;

    // 更新全局变量（如果其他地方需要）
    currentPanAngle = panAngle;
    currentTiltAngle = tiltAngle;
}

// 统一处理UI禁用/启用的函数
function disableUI(disable) {
    const buttons = document.querySelectorAll('button');
    buttons.forEach(button => {
        button.disabled = disable;
    });
    const sliders = document.querySelectorAll('input[type="range"]');
    sliders.forEach(slider => {
        slider.disabled = disable;
    });
}

// 统一处理状态反馈动画
function handleFeedbackAnimation(element, success) {
    element.classList.remove('success-animation', 'error-animation');
    // 强制重绘以重启动画
    void element.offsetWidth;
    if (success) {
        element.classList.add('success-animation');
    } else {
        element.classList.add('error-animation');
    }
    // 动画结束后移除类（可选，取决于CSS）
    setTimeout(() => {
        element.classList.remove('success-animation', 'error-animation');
    }, 1000);
}

// 人脸自动跟踪开关
let trackingEnabled = false;

// 禁用所有按钮 - 这个函数现在被 disableUI 替代
// function disableButtons(disable) {
//     const buttons = document.querySelectorAll('button');
//     buttons.forEach(button => {
//         button.disabled = disable;
//     });
// }

// 切换人脸跟踪功能
function toggleFaceTracking() {
    // 获取按钮元素
    const trackButton = document.getElementById('track-face-btn');
    
    // 显示状态信息
    const statusElement = document.getElementById('status');
    const action = trackingEnabled ? '停止' : '启动';
    statusElement.innerText = `正在${action}人脸跟踪，请稍候...`;
    
    // 禁用所有按钮，防止重复操作
    disableUI(true);
    
    // 发送切换跟踪请求
    fetch('/toggle_tracking', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            enabled: !trackingEnabled
        })
    })
    .then(response => response.json())
    .then(data => {
        // 更新状态信息
        statusElement.innerText = data.message;
        
        if (data.success) {
            // 更新跟踪状态
            trackingEnabled = data.state;
            
            // 更新按钮文本
            trackButton.innerText = trackingEnabled ? '停用人脸跟踪' : '启用人脸跟踪';
            
            // 如果启用跟踪，禁用舵机滑块控制
            const sliders = document.querySelectorAll('input[type="range"]');
            sliders.forEach(slider => {
                slider.disabled = trackingEnabled;
            });
            
            // 添加成功反馈动画
            statusElement.classList.add('success-animation');
            setTimeout(() => {
                statusElement.classList.remove('success-animation');
            }, 1000);
            
            // 3秒后更新状态信息
            setTimeout(() => {
                const status = trackingEnabled ? 
                    '人脸自动跟踪已启用，系统将自动跟踪检测到的人脸' : 
                    '系统就绪，使用滑块控制舵机位置';
                statusElement.innerText = status;
            }, 3000);
        } else {
            // 添加失败反馈动画
            statusElement.classList.add('error-animation');
            setTimeout(() => {
                statusElement.classList.remove('error-animation');
            }, 1000);
            
            // 3秒后更新状态信息
            setTimeout(() => {
                statusElement.innerText = '系统就绪，使用滑块控制舵机位置';
            }, 3000);
        }
        
        // 重新启用按钮
        disableUI(false);
    })
    .catch((error) => {
        console.error('Error:', error);
        statusElement.innerText = '切换人脸跟踪失败: ' + error;
        
        // 添加失败反馈动画
        statusElement.classList.add('error-animation');
        setTimeout(() => {
            statusElement.classList.remove('error-animation');
        }, 1000);
        
        // 重新启用按钮
        disableUI(false);
    });
} 